using System.Linq;
using Jy.Abp.Localization;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Localization;

namespace Jy.Abp.Authorization;

public class TypedPermissionDefinitionProvider : PermissionDefinitionProvider
{
    private readonly IResourceTypeProvider _resourceTypeFinder;
    public TypedPermissionDefinitionProvider(IResourceTypeProvider resourceTypeFinder)
    {
        _resourceTypeFinder = resourceTypeFinder;
    }

    public ILocalizableString GetDisplayName(PermissionGroupAttribute define)
    {
        var displayName = define.DisplayName;
        if (displayName == null)
        {
            var resourceType = this._resourceTypeFinder.GetResourceType(define.DeclaringType);
            if (resourceType != null)
                displayName = LocalizableString.Create(resourceType, define.DisplayNameKey);
        }
        return displayName;
    }

    public override void Define(IPermissionDefinitionContext context)
    {
        var contextInfo = context as PermissionDefinitionContext;
        foreach (var groupType in PermissionHelper.GroupTypes)
        {
            var groupDefine = PermissionHelper.GetGroup(groupType);
            var group = contextInfo
                .Groups
                .FirstOrDefault(t => t.Key == groupDefine.Name)
                .Value;
            if (group == null)
                group = context.AddGroup(groupDefine.Name, GetDisplayName(groupDefine));

            var permissionTypes = groupType
                    .GetNestedTypes()
                    .Where(t => t.IsEnum);
            foreach (var permissionType in permissionTypes)
            {
                var define = PermissionHelper.GetDefine(permissionType);
                var permission = group.AddPermission(define.Name, GetDisplayName(define), define.MultiTenancySides);
                //处理枚举值
                foreach (var field in permissionType.GetFields().Where(t => t.Name != "value__"))
                {
                    var cDefine = PermissionHelper.GetDefine(field);
                    var p = permission.AddChild(cDefine.Name, GetDisplayName(cDefine), cDefine.MultiTenancySides);
                }
            }
        }
    }
}
